package hash;

import org.junit.Test;

/**
 * @author kunkun
 * @className LeetCode_41
 * @Description 缺失的第一个正数
 * @date 2025/3/12 12:14
 */
public class LeetCode_41 {
    public int firstMissingPositive(int[] nums) {
        return solution(nums);
    }

    @Test
    public void test(){
//        System.out.println(firstMissingPositive(new int[]{3, 4, -1, 1}));//2
        System.out.println(firstMissingPositive(new int[]{1,1}));//2
//        System.out.println(firstMissingPositive(new int[]{-1, -2, -2, -1}));//1
//        System.out.println(firstMissingPositive(new int[]{1}));//2
    }

    /**
    * @Description: 自定义hash规则解决
    * @Author: kunkun
    * @Date:  2025/3/12 12:15
    * @Parameters:
    * @Return
    * @Throws
    */
    public int solution(int[] nums){
        //1. 自定义hash规则
        for (int i = 0; i < nums.length; i++) {
            //判断规则
            if (nums[i]<=nums.length && nums[i]>0 && nums[i]!=i+1){
                //交换
                if (nums[nums[i]-1]!=nums[i]){
                    swap(nums,i,nums[i]-1);
                    i--;
                }
            }
        }

        //输出
        int i=0;
        for (i = 0; i < nums.length; i++) {
            if (nums[i]!=i+1){
                return i+1;
            }
        }

        return i+1;
    }

    public void swap(int[] nums,int i,int j){
        if (i==j){
            return;
        }
        int temp = nums[j];
        nums[j]=nums[i];
        nums[i]=temp;
    }

}
